package com.ec.auth.config;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import com.ec.common.utils.Threads;

/**
 * 线程池配置
 * 用于处理线程相关的操作
 * @author ec
 **/
@Configuration
public class ThreadPoolConfig {
    // 核心线程池大小
    private int corePoolSize = 50;

    // 最大可创建的线程数
    private int maxPoolSize = 200;

    // 队列最大长度
    private int queueCapacity = 1000;

    // 线程池维护线程所允许的空闲时间
    private int keepAliveSeconds = 300;


    /**
     * 这是一个创建 ThreadPoolTaskExecutor 的方法
     * @return
     */
    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        // 实例化 ThreadPoolTaskExecutor 对象
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置最大线程池大小、核心线程池大小、队列容量和空闲时间
        executor.setMaxPoolSize(maxPoolSize);
        executor.setCorePoolSize(corePoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // 线程池对拒绝任务(无线程可用)的处理策略
        // 设置拒绝任务的处理策略为CallerRunsPolicy，表示当线程池已满且任务被拒绝时，调用任务的执行器会直接执行该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }

    /**
     * 执行周期性或定时任务
     * Bean name is  scheduledExecutorService
     * 实例化 ScheduledThreadPoolExecutor 对象，使用核心线程数和一个自定义的线程工厂
     * new BasicThreadFactory是使用了builder模式
     */
    @Bean(name = "scheduledExecutorService")
    protected ScheduledExecutorService scheduledExecutorService() {
        return new ScheduledThreadPoolExecutor(
                corePoolSize,
                new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build()
        ) {
            // 重写了 afterExecute 方法，在任务执行完毕后进行一些额外的处理，比如打印异常信息
            // lambda表达式?
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
                Threads.printException(r, t);
            }
        };
    }
}
